package calbs.socket.server.decoder;

import calbs.socket.server.cache.UserCache;
import calbs.socket.tool.Byte2Hex;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.logging.Logger;

public class Bytes2HexDecoder extends ByteToMessageDecoder{

	private org.slf4j.Logger logger = LoggerFactory.getLogger(Bytes2HexDecoder.class);
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
		byte[] req = new byte[in.readableBytes()];
		in.readBytes(req);
		String message = Byte2Hex.Bytes2HexString(req);
		if(message.startsWith("7E7D")&&!message.endsWith("7E7D")){
			UserCache.clearMessage(ctx.channel());
			UserCache.linkMessage(ctx.channel(),message);
		}else if(!message.startsWith("7E7D")&&!message.endsWith("7E7D")){
			UserCache.linkMessage(ctx.channel(),message);
		}else if((!message.startsWith("7E7D")&&message.endsWith("7E7D"))||message.equals("7E7D")){
			UserCache.linkMessage(ctx.channel(),message);
			logger.info("传输协议粘包处理：{}",UserCache.getLinkMessage(ctx.channel()));
			out.add(UserCache.getLinkMessage(ctx.channel()));
			UserCache.clearMessage(ctx.channel());
		} else if(message.startsWith("7E7D")&&message.endsWith("7E7D")&&!message.equals("7E7D")){
			UserCache.clearMessage(ctx.channel());
			logger.info("传输协议处理：{}",message);
			out.add(message);
		}

	}

}
